package eu.news.servlet.admin.news;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import eu.jk.base.security.AuthFilter;
import eu.news.config.Debugger;
import eu.news.data.hibernate.dao.HB_NewsDAO;
import eu.news.data.hibernate.dao.HB_PictureDAO;
import eu.news.data.hibernate.dao.HB_SortDAO;
import eu.news.data.hibernate.dao.HB_SpecialDAO;
import eu.news.data.hibernate.pojo.HB_News;
import eu.news.data.pojo.Operator;
import eu.news.data.pojo.Picture;
import eu.news.data.pojo.Sort;
import eu.news.data.pojo.Special;
import eu.news.index.NewsIndexDAO;
import eu.news.kits.SecurityManager;
import eu.news.template.NewsStatic;

/**
 * Servlet implementation class UpdateNews
 */
public class UpdateNews extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateNews() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HB_News news=authAndGetNews(request, response);
		if(news==null){
			response.sendError(401);
			return;
		}
		boolean save=request.getParameter("save")!=null;
		boolean publish=request.getParameter("publish")!=null;
		if(!(save||publish)){
			response.sendError(404);
			Debugger.println("获取指令失败");
			return;
		}
		HB_NewsDAO neDao=new HB_NewsDAO();
		if(publish){
			if(news.getOperator().getType()==Operator.TYPE.UNAUTH_EDITOR){
				news.setState(News.State.STATE_UNVERIFIED);
				request.setAttribute("message", "新闻正在等待审核");
			}else{
				request.setAttribute("message", "成功发布新闻");
				news.setState(News.State.STATE_PUBLISHED);
			}
			if(news.getId()<0)
				neDao.save(news);
			else
				neDao.update(neDao.merge(news));
			NewsStatic.deleteData(news.getId());
			NewsIndexDAO.updateIndex(news);
			neDao.commit();
			neDao.refresh(news);
		}
		if(save){
			news.setState(News.State.STATE_EDIT);
			if(news.getId()<0)
				neDao.save(news);
			else
				neDao.update(neDao.merge(news));
			neDao.commit();
			neDao.refresh(news);
			request.setAttribute("message", "成功保存为草稿");
		}
		request.setAttribute("news", news);
		request.setAttribute("op", news.getOperator());
		request.setAttribute("sp", news.getSort().getSpecial());
		if(news.getType()==News.Type.NORMAL)
			request.getRequestDispatcher("/admin/face/news/news.jsp").forward(request, response);
		else 
			request.getRequestDispatcher("/admin/face/news/pic_news.jsp").forward(request, response);
	}

	/**
	 * 验证并获取新闻
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	private HB_News authAndGetNews(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String uri=request.getRequestURI();
		String[] fields=uri.split("/");
		String specialName=URLDecoder.decode(fields[fields.length-2],"UTF-8");
		String sortId=request.getParameter("sort");
		Operator operator=SecurityManager.getOperator(request);
		/*
		 * 验证访问合法性
		 * 1、专题，分类是否找到
		 * 2、用户是否有权限操作
		 */
		HB_SpecialDAO spDao=new HB_SpecialDAO();
		Special special=spDao.getByName(specialName);
		if(special==null){
			Debugger.println("获取Special失败");
			return null;
		}
		HB_SortDAO stDao=new HB_SortDAO();
		Sort sort=stDao.getById(Integer.parseInt(sortId));
		if(sort==null){
			Debugger.println("获取Sort失败");
			return null;
		}
		if(!special.getSorts().contains(sort)||!operator.getSorts().contains(sort)){
			System.out.println(special);
			System.out.println(sort);
			System.out.println(operator);
			Debugger.println("无权限");
			return null;
		}
		if(uri.endsWith("text"))
			return doNormalNews(request, sort, operator);
		else if(uri.endsWith("picture"))
			return doPictureNews(request, sort, operator);
		return null;
	}
	
	private HB_News doNormalNews(HttpServletRequest request,Sort sort,Operator operator){
		//更新News实体
		HB_News news=new HB_News();
		news.setTitle(request.getParameter("title"));
		news.setContent(request.getParameter("content"));
		news.setSort(sort);
		news.setOperator(operator);
		news.setTime(new Date());
		String _nid=request.getParameter("id");
		if(_nid.length()>0)
			news.setId(Integer.parseInt(_nid));
		else
			news.setId(-1);
		news.setType(News.Type.NORMAL);
		return news;
	}
	
	private HB_News doPictureNews(HttpServletRequest request,Sort sort,Operator operator){
		HB_News news=new HB_News();
		news.setTitle(request.getParameter("title"));
		news.setSort(sort);
		news.setOperator(operator);
		news.setTime(new Date());
		String _nid=request.getParameter("id");
		if(_nid!=null&&_nid.length()>0)
			news.setId(Integer.parseInt(_nid));
		else
			news.setId(-1);
		news.setType(News.Type.PICTURE);
		//分割字符串
		String _pic=request.getParameter("picture");
		StringBuffer buffer=new StringBuffer();
		int index=_pic.indexOf(">");
		int array_index=0;
		String[] pictures=new String[Integer.parseInt(_pic.substring(0,index))];
		index++;
		char pre_char='\0';
		char c='\0';
		while(index<_pic.length()){
			c=_pic.charAt(index);
			index++;
			if(c==';'){
				if(pre_char!='\\'){
					pictures[array_index]=buffer.toString();
					array_index++;
					buffer.delete(0, buffer.length());
					continue;
				}else{
					buffer.deleteCharAt(index-2);
				}
			}
			buffer.append(c);
		}
		//处理图片
		HB_PictureDAO pDao=new HB_PictureDAO();
		for(String picture:pictures){
			if(picture.startsWith("!"))
				//TODO 删除不需要的上传图片
				continue;
			String pid=picture.substring(0,picture.indexOf(":"));
			String remark=picture.replace(pid+":", "");
			if(!AuthFilter.isDigit(pid))
				continue;
			Picture pic=pDao.getById(Integer.parseInt(pid));
			if(pic==null)
				//TODO 复制已经存在的图片
				continue;
			pic.setRemark(remark);
			news.getPictures().add(pic);
			pic.setNews(news);
		}
		return news;
	}
}
